package com.fh.controller.ccode.solution;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fh.controller.base.BaseController;
import com.fh.service.ccode.AppCcodeUserService;
import com.fh.service.ccode.SolutionService;
import com.fh.util.AppUtil;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.DelAllFile;
import com.fh.util.PageData;
import com.fh.util.PathUtil;
import com.fh.util.JGit.JGitUtil;
import com.fh.util.cloc.ClocUtil;
import com.fh.util.cloc.ClocUtil.queryResult;
import com.sine_x.jcloc.JCloc;
import com.sine_x.jcloc.Report;

@Controller
@RequestMapping(value = "/appsolution")
public class SolutionController extends BaseController {

	@Resource(name = "solutionService")
	private SolutionService solutionService;
	
	@Resource(name = "appCcodeUserService")
	private AppCcodeUserService appCcodeUserService;

	@RequestMapping(value = "/getMissionPerson")
	@ResponseBody
	public Object getMissionPerson(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		try {
			List<PageData> list = solutionService.getMissionPerson(pd);
			List<PageData> tempList = new ArrayList<PageData>();

			for (int i = 0; i < list.size(); i++) {
				PageData tempPD = new PageData();
 				tempPD.put("avatarUrl", list.get(i).getString("HEAD_URL"));
				tempPD.put("name", list.get(i).getString("NAME"));
				tempPD.put("school", list.get(i).getString("DEPARTNAME"));
				tempPD.put("applyMoney", list.get(i).get("APPLYMONEY") + "");
				tempPD.put("star", list.get(i).get("STAR") + "");
				tempPD.put("solutionName", list.get(i).getString("S_TITLE"));
				tempPD.put("admited", list.get(i).get("ADMITED") + "");
				tempPD.put("solutionID", list.get(i).get("SOLUTION_ID") + "");

				tempList.add(tempPD);
			}

			map.put("data", tempList);
			map.put("code", "T");
			map.put("msg", "获取学生信息成功");
			
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "获取学生信息失败");
		}

		return AppUtil.returnObject(new PageData(), map);
	}

	@RequestMapping(value = "/addSolution")
	@ResponseBody
	public Object addSolution(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String, Object> map = new HashMap<String, Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		pd.put("postTime", df.format(new Date()));

		try {
			PageData tempPD = appCcodeUserService.getInfoByToken(pd);
			pd.put("posterID", tempPD.get("C_USER_ID"));
			
			solutionService.addSolution(pd);
			map.put("code", "T");
			map.put("msg", "添加方案成功");

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "添加方案失败");
		}

		return AppUtil.returnObject(new PageData(), map);

	}

	@RequestMapping(value = "/solist")
	@ResponseBody
	public Object getSolutionList(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String, Object> map = new HashMap<String, Object>();

		PageData pd = new PageData();
		pd = this.getPageData();
		
		int start = (Integer.parseInt(pd.getString("pageNum")) - 1) * Integer.parseInt(pd.getString("pageSize"));
		pd.put("start", start);

		int size = Integer.parseInt(pd.getString("pageSize"));
		pd.put("size", size);

		pd.remove("pageNum");
		pd.remove("pageSize");

		try {
			List<PageData> list = solutionService.getSolutionList(pd);

			List<PageData> tempList = new ArrayList<PageData>();

			for (int i = 0; i < list.size(); i++) {
				PageData tempPD = new PageData();
				tempPD.put("title", list.get(i).getString("S_TITLE"));
				tempPD.put("avatarUrl", list.get(i).getString("HEAD_URL"));
				tempPD.put("detail", list.get(i).getString("S_DESCRIPTION"));
				tempPD.put("className", list.get(i).getString("CLASS_NAME"));
				tempPD.put("writer", list.get(i).getString("NAME"));
				tempPD.put("money", list.get(i).get("APPLYMONEY") + "");
				tempPD.put("id", list.get(i).get("SOLUTION_ID") + "");

				tempList.add(tempPD);
			}
			map.put("data", tempList);
			map.put("code", "T");
			map.put("msg", "获取方案列表成功");

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "T");
			map.put("msg", "获取方案列表失败");			
		}

		return AppUtil.returnObject(new PageData(), map);
	}
	
	@RequestMapping(value="/getOneSolution")
	@ResponseBody
	public Object getOneSolution(HttpServletRequest request,HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object>map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		try
		{
			// 权限验证
			if (solutionService.checkPermission(pd) == 0) {
				map.put("code", "F");
				map.put("msg", "权限不足");
				return AppUtil.returnObject(new PageData(), map);
			}
			
			pd = solutionService.getOneSolution(pd);
			
			PageData tempPD = new PageData();
			tempPD.put("title", pd.getString("S_TITLE"));
			tempPD.put("publishTime", df.format(pd.get("S_POSTTIME")));
			tempPD.put("className", pd.getString("CLASS_NAME"));
			tempPD.put("writer", pd.getString("NAME"));
			tempPD.put("writerID", pd.get("C_USER_ID") + "");
			tempPD.put("content", pd.getString("S_DESCRIPTION"));
			
			map.put("data", tempPD);
			map.put("code", "T");
			map.put("msg", "获取方案信息成功");
			
		}catch(Exception e)
		{
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "获取方案信息失败");
		}
		
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	@RequestMapping(value="/addSoComment")
	@ResponseBody
	public Object addSoComment(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String, Object> map = new HashMap<String, Object>();

		PageData pd = new PageData();
		pd = this.getPageData();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		pd.put("posttime", df.format(new Date()));

		try {
			// 权限验证
			if (solutionService.checkPermission(pd) == 0) {
				map.put("code", "F");
				map.put("msg", "权限不足");
				return AppUtil.returnObject(new PageData(), map);
			}
			
			PageData tempPD = appCcodeUserService.getInfoByToken(pd);
			pd.put("userID", tempPD.get("C_USER_ID"));
			
			solutionService.addComment(pd);
			map.put("code", "T");
			map.put("msg", "添加评论成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "添加评论失败");
		}

		return AppUtil.returnObject(new PageData(), map);
	}
	
	@RequestMapping(value="/getSoComments")
	@ResponseBody
	public Object getMiComments(HttpServletRequest request,HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> map = new HashMap<String,Object>();
		
		PageData pd = new PageData();
		pd = this.getPageData();
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		try{
			// 权限验证
			if (solutionService.checkPermission(pd) == 0) {
				map.put("code", "F");
				map.put("msg", "权限不足");
				return AppUtil.returnObject(new PageData(), map);
			}
			
			List<PageData> list = solutionService.getSoComments(pd);
			List<PageData> tempList = new ArrayList<PageData>();
			
			for(int i = 0; i < list.size(); i++)
			{
				PageData tempPD = new PageData();
				tempPD.put("avatarUrl", list.get(i).getString("HEAD_URL"));
				tempPD.put("name", list.get(i).getString("NAME"));
				tempPD.put("time", df.format(list.get(i).get("SO_COMMENT_POSTTIME")));
				tempPD.put("content", list.get(i).getString("SO_COMMENT_CONTENT"));
				
				tempList.add(tempPD);
			}
			map.put("data", tempList);
			map.put("code", "T");
			map.put("msg", "获取任务评论成功");
			
		}catch(Exception e)
		{
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "获取任务评论失败");
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	@RequestMapping(value="/gitAddr")
	@ResponseBody
	public Object getGitAddr(HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SOLUTION_ID", pd.getString("id"));
		
		
		try{
			// 权限验证
			if (solutionService.checkPermission(pd) == 0) {
				map.put("code", "F");
				map.put("msg", "权限不足");
				return AppUtil.returnObject(new PageData(), map);
			}
			
			pd = solutionService.getOneSolution(pd);
			PageData temp = new PageData();
			temp.put("url", pd.getString("GIT_ADDR"));
			temp.put("cloning", pd.get("GITCLONE_STATUS") + "");
			// Info
			String info = "";
			switch ((Integer) pd.get("GITCLONE_STATUS")) {
			case 0:
				info = "分析未开始";
				break;
			case 1:
				info = "正在Clone与分析代码";
				// 同时去查一下
				queryResult qResult = ClocUtil.queryTask((Integer) pd.get("SOLUTION_ID"));
				if(!qResult.success){
					break;
				}else{
					solutionService.updateCloneStatusToTrue(pd);
				}
				// 成功的话Clone完成
			case 2:
				info = "代码分析完成";
				break;
			default:
				break;
			}
			temp.put("statusinfo", info);
//			temp.put("lastClone", DateUtil.formatTime(pd.get("GITCLONE_LASTUPDATE")));
			temp.put("description", pd.getString("GIT_DESCRIPTION"));
			map.put("data", temp);
			map.put("code", "T");
			map.put("msg", "获取GIT地址成功");
			
		}catch(Exception e){
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "获取GIT地址失败");
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}

	
	@RequestMapping(value="/addGit")
	@ResponseBody
	public Object addGitAddr(HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SOLUTION_ID", pd.getString("id"));
		
		try{
			// 权限验证
			if (solutionService.checkPermission(pd) == 0) {
				map.put("code", "F");
				map.put("msg", "权限不足");
				return AppUtil.returnObject(new PageData(), map);
			}
			
			solutionService.updateCloneStatusToDefault(pd);
			solutionService.addGitInfo(pd);
			
			map.put("code", "T");
			map.put("msg", "添加GIT信息成功");
			
		}catch(Exception e){
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "添加GIT信息失败");
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	@RequestMapping(value="/gitClone")
	@ResponseBody
	public Object gitClone(HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		try{
			// 权限验证
			if (solutionService.checkPermission(pd) == 0) {
				map.put("code", "F");
				map.put("msg", "权限不足");
				return AppUtil.returnObject(new PageData(), map);
			}
			
			solutionService.updateCloneStatusToFalse(pd);
			
			pd = solutionService.getOneSolution(pd);
			int solutionID = (Integer) pd.get("SOLUTION_ID");
			String gitUrl = pd.getString("GIT_ADDR");
			String soID = solutionID + "";
			String username = pd.getString("GIT_USERNAME");
			String password = pd.getString("GIT_PASSWORD");
			
			if(null != gitUrl && !gitUrl.isEmpty())
			{
				pd.put("updateTime", DateUtil.getTime());
				solutionService.updateCloneStatusToFalse(pd);
				// 发送下载Task的命令
				ClocUtil.addTask(solutionID, gitUrl, username, password);
				map.put("code", "T");
				map.put("msg", "已发送Git Clone请求");
				
			}else{
				map.put("code", "F");
				map.put("msg", "没有添加GIT地址");
			} 
			
		}catch(Exception e){
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "Git Clone失败");
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	// 查询代码分析结果
	@RequestMapping(value="/queryCode")
	@ResponseBody
	public Object queryCode(HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		int solutionId = Integer.parseInt(pd.getString("id"));
		pd.put("SOLUTION_ID", solutionId);
		
		PageData temppd = new PageData();
			
		try{
			// 权限验证
			if (solutionService.checkPermission(pd) == 0) {
				map.put("code", "F");
				map.put("msg", "权限不足");
				return AppUtil.returnObject(new PageData(), map);
			}
			
			PageData checkStatusPd = solutionService.getOneSolution(pd);
			int status = (Integer) checkStatusPd.get("GITCLONE_STATUS");
			if(status == 0){
				map.put("code", "T");
				map.put("msg", "未计算");
				
				temppd.put("empty", 0 + "");
				temppd.put("comment", 0 + "");
				temppd.put("real", 0 + "");
				temppd.put("all", 0+"");
				
				map.put("data", temppd);
				
				return AppUtil.returnObject(new PageData(), map);
			}
			// 先去Cloc查询结果
			queryResult qResult = ClocUtil.queryTask(solutionId);
			// 是否成功
			if(qResult.success){
				solutionService.updateCloneStatusToTrue(pd);
				// 保存查询信息
				pd.put("codeline", qResult.code);
				pd.put("comment", qResult.comment);
				pd.put("blank", qResult.blank);
				pd.put("hashStr", qResult.simhashCode);
				solutionService.saveCodeInfo(pd);
				// 查询相似Code
				List<PageData> lPageDatas = solutionService.getSimilar(pd);
				List<PageData> tempList = new ArrayList<PageData>();
				// 返回结果
				for(int i = 0;i < lPageDatas.size();i++){
					PageData temp = new PageData();
					temp.put("id", lPageDatas.get(i).get("SOLUTION_ID"));
					temp.put("avatarUrl", lPageDatas.get(i).get("AVATAR_URL"));
					temp.put("solutionName", lPageDatas.get(i).get("S_TITLE"));
					temp.put("gitUrl", lPageDatas.get(i).get("GIT_ADDR"));
					temp.put("Hamming", lPageDatas.get(i).get("hamming_distance"));
					tempList.add(temp);
				}
				temppd.put("similarity", tempList);
				map.put("code", "T");
				map.put("msg", "获取code分析信息成功");
				
			}else{
				map.put("code", "T");
				map.put("msg", "正在计算中");
				
			}
			pd = solutionService.getOneSolution(pd);
			int blank = (Integer) (pd.get("CODE_BLANK")!=null ? pd.get("CODE_BLANK") : 0);
			int comment = (Integer) (pd.get("CODE_COMMENT")!=null ? pd.get("CODE_COMMENT") : 0);
			int real = (Integer) (pd.get("CODE_REAL")!=null ? pd.get("CODE_REAL") : 0);
			temppd.put("empty", blank + "");
			temppd.put("comment", comment + "");
			temppd.put("real", real + "");
			temppd.put("all", real + blank + comment);
			
			map.put("data", temppd);
			
		}catch(Exception e){
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "查询代码分析结果失败");
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}

}
